# -*- coding:utf-8 -*-

# @Time    : 2023/8/5 20:34
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @File    : history_data_script.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

import pandas as pd
from bot.insurance_planner_gpt.planner import PlannerChat

session_id_path = "/Users/zengwenjia/Downloads/session_id.txt"

async def read_data():
    result = pd.read_excel("/Users/zengwenjia/Downloads/conversation_2023-07-24.xlsx")
    # 按对话id将"角色"和"对话内容"成对话上下文的list,上下文的格式是[角色：对话内容,角色：对话内容]

    result = result.groupby('对话id').agg({'角色':lambda x: list(x), '对话内容':lambda x: list(x)})
    result = result.reset_index()
    result['上下文'] = None
    bot = PlannerChat(None)
    # 读取session_id_path文件中的session_id
    session_id_list = []
    with open(session_id_path, "r") as f:
        session_id_list = f.readlines()
        session_id_list = [session_id.strip() for session_id in session_id_list]

    
    for i in range(len(result)):
        context = []
        session_id = str(result['对话id'][i])
        if session_id in session_id_list:
            continue
        print(session_id)
        for j in range(len(result['角色'][i])):
            conversation_dict = {}
            conversation_dict["role"] = result['角色'][i][j]
            conversation_dict["content"] = result['对话内容'][i][j]
            context.append(conversation_dict)
            if conversation_dict["role"] == "user":
                history = bot.planner.format_conversation_history(context)
                res, other_message = await bot.planner.async_reply(history, session_id, "test", is_stream=False)
        session_id_list.append(session_id)
        # 将session_id_list写入文件
        with open(session_id_path, "w") as f:
            for session_id in session_id_list:
                f.write(session_id + "\n")
        
        # result['上下文'][i] = [result['角色'][i][j] + ':' + result['对话内容'][i][j] for j in range(len(result['角色'][i]))]
        # print(result['上下文'][i])

    print(result)

if __name__ == '__main__':
    import asyncio
    result = asyncio.run(read_data())

